from pptx import Presentation
from pptx.util import Inches, Pt
from pptx.enum.chart import XL_CHART_TYPE
from pptx.chart.data import CategoryChartData


def _textbox(slide, x, y, w, h, text):
    box = slide.shapes.add_textbox(Inches(x), Inches(y), Inches(w), Inches(h))
    tf = box.text_frame
    tf.clear()
    p = tf.paragraphs[0]
    p.text = text
    return box


def _add_chart(slide, x, y, w, h):
    data = CategoryChartData()
    data.categories = ["Q1", "Q2", "Q3", "Q4"]
    data.add_series("示例A", (1, 2, 3, 4))
    data.add_series("示例B", (2, 2, 3, 5))
    chart = slide.shapes.add_chart(
        XL_CHART_TYPE.COLUMN_CLUSTERED,
        Inches(x), Inches(y), Inches(w), Inches(h), data
    ).chart
    return chart


def _add_table(slide, x, y, w, h, rows=6, cols=3):
    shape = slide.shapes.add_table(rows, cols, Inches(x), Inches(y), Inches(w), Inches(h))
    return shape.table


def generate(out_path: str):
    from pathlib import Path
    Path(out_path).parent.mkdir(parents=True, exist_ok=True)
    prs = Presentation()

    # 封面
    cover = prs.slides.add_slide(prs.slide_layouts[6])
    _textbox(cover, 0.1, 0.1, 1.5, 0.3, "{{slide:cover}}")
    _textbox(cover, 1.0, 1.5, 8.0, 1.0, "{{title}}")
    _textbox(cover, 1.0, 2.6, 8.0, 0.8, "{{subtitle}}")
    _textbox(cover, 1.0, 3.5, 8.0, 0.6, "{{caption}}")
    _textbox(cover, 8.5, 0.5, 1.5, 1.5, "{{image.logo}}")

    # 目录
    toc = prs.slides.add_slide(prs.slide_layouts[6])
    _textbox(toc, 0.1, 0.1, 1.5, 0.3, "{{slide:toc}}")
    _textbox(toc, 1.0, 1.0, 8.0, 0.8, "目录")
    _textbox(toc, 1.0, 1.9, 8.0, 4.5, "{{list.bullets}}")

    # 概述/章节页
    section = prs.slides.add_slide(prs.slide_layouts[6])
    _textbox(section, 0.1, 0.1, 1.5, 0.3, "{{slide:section}}")
    _textbox(section, 1.0, 1.0, 8.0, 0.8, "{{heading}}")
    _textbox(section, 1.0, 1.9, 8.0, 4.5, "{{content}}")

    # 图表页
    chart_page = prs.slides.add_slide(prs.slide_layouts[6])
    _textbox(chart_page, 0.1, 0.1, 1.5, 0.3, "{{slide:chart_page}}")
    _textbox(chart_page, 1.0, 1.0, 8.0, 0.5, "销售数据")
    _textbox(chart_page, 1.0, 1.6, 2.0, 0.4, "{{chart.sales}}")
    _add_chart(chart_page, 1.0, 2.1, 8.0, 4.0)

    # 联系页（表格）
    contact = prs.slides.add_slide(prs.slide_layouts[6])
    _textbox(contact, 0.1, 0.1, 1.5, 0.3, "{{slide:contact}}")
    _textbox(contact, 1.0, 1.0, 8.0, 0.8, "{{title}}")
    _textbox(contact, 1.0, 1.9, 2.0, 0.4, "{{table.members}}")
    tbl = _add_table(contact, 1.0, 2.4, 8.0, 3.0, rows=6, cols=3)
    tbl.cell(0, 0).text = "姓名"
    tbl.cell(0, 1).text = "职责"
    tbl.cell(0, 2).text = "邮箱"

    prs.save(out_path)


if __name__ == "__main__":
    import argparse

    ap = argparse.ArgumentParser()
    ap.add_argument("--out", default="templates/standard_template.pptx")
    args = ap.parse_args()
    generate(args.out)